package com.salt.modules.sys.service;

import com.salt.common.service.CrudService;
import com.salt.common.utils.StringUtils;
import com.salt.core.oss.OssTemplate;
import com.salt.core.persistence.Page;
import com.salt.modules.sys.entity.SystemFile;
import com.salt.modules.sys.mapper.SystemFileMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @Author salt
 * @Date 2022/3/28
 * @Version 1.0.1
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class SystemFileService extends CrudService<SystemFileMapper, SystemFile> {

    private final OssTemplate ossTemplate;

    public SystemFile get(String id) {
        if (StringUtils.isNotBlank(id)) {
            return mapper.get(id);
        }
        return new SystemFile();
    }

    @Transactional(readOnly = false)
    public void delete(SystemFile systemFile) {
        mapper.delete(systemFile);
        if (StringUtils.isNotBlank(systemFile.getName()))
            ossTemplate.removeFile(systemFile.getName());
    }

    public Page<SystemFile> findPage(Page<SystemFile> page, SystemFile systemFile) {
        List<SystemFile> files = mapper.findList(systemFile);
        if (files != null && !files.isEmpty()) {
            page.setCount(files.size());
            if (page.getMaxResults() != -1) {
                files = files.subList(page.getFirstResult(), page.getLastResult());
            }
            files.stream().forEach(file -> file.setLink(ossTemplate.fileLink(file.getName())));
            page.setList(files);
        }
        return page;
    }

    public SystemFile find(SystemFile systemFile) {
        SystemFile file = mapper.find(systemFile);
        if (file != null) {
            //file.setLink(ossTemplate.outerFileLink(file.getName()));
            file.setLink(ossTemplate.fileLink(file.getName()));
            return file;
        }
        return systemFile;
    }

    public List<SystemFile> findList(SystemFile systemFile) {
        List<SystemFile> files = mapper.findList(systemFile);
        if (files != null && !files.isEmpty()) {
            files.stream().forEach(file -> file.setLink(ossTemplate.fileLink(file.getName())));
        }
        return files;
    }

    @Transactional(readOnly = false)
    public int deleteByLogic(SystemFile tnpmFile) {
        return mapper.deleteByLogic(tnpmFile);
    }

    @Transactional(readOnly = false)
    public void insertBatch(List<SystemFile> fileList) {
        mapper.insertBatch(fileList);
    }
}
